package com.gopay.scheduler.job;

import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.service.cbrmb.CbRmbIntlCardSettleAmtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.*;

/**
 * 外卡订单清算金额计算
 * 
 * @ClassName: CbRmbIntlCardSettleAmtJob
 * @author b.zou
 * @date 2017-11-7
 */
public class CbRmbIntlCardSettleAmtJob extends GopayBaseJob {

	private Logger logger = LoggerFactory.getLogger(CbRmbIntlCardSettleAmtJob.class);

	/**
	 * 结算时间为3天，查3天之前的所有订单
	 */
	private static final int CIRCLE_DAYS = 3;

	/**
	 * 公共查询Dao
	 */
	@Resource(name = "commonQueryDAO")
	private CommonQueryDAO commonQueryDAO;

	@Resource(name = "cbRmbIntlCardSettleAmtService")
	private CbRmbIntlCardSettleAmtService cbRmbIntlCardSettleAmtService;


	@Override
	protected void doJobInternal() {
		logger.info("-------CbRmbIntlCardSettleAmtJob Start-------");
		List<String> list = getResult();
		if(list.isEmpty()){
			logger.info("-------没有需要更新清算金额的外卡订单-------");
		}else{
			logger.info("-------有{}笔需要更新清算金额的外卡订单-------",list.size());
			for (String orderId : list) {
				cbRmbIntlCardSettleAmtService.updateSettleAmt(orderId);
			}
			logger.info("-------更新外卡订单清算金额完成-------");
		}
		logger.info("-------CbRmbIntlCardSettleAmtJob Stop-------");
	}

	private List<String> getResult() {
		List<String> list = new ArrayList<>();
		// 计算T-30的日期
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -CIRCLE_DAYS);
		String paramTime = DateUtils.format(calendar.getTime(), "yyyyMMdd") + "000000";
		StringBuffer sql = new StringBuffer();
		sql.append(" select main.gopay_order_id,main.gopay_int_txn_cd,intl.settle_flag ");
		sql.append(" from cps_gen_main_order main,cb_rmb_wild_card_assist_dtl intl ");
		sql.append(" where main.gopay_order_id=intl.gopay_order_id ");
		sql.append(" and main.gopay_int_txn_cd='01740' ");
		sql.append(" and main.txn_sta_cd='20000' ");
		sql.append(" and intl.settle_flag='0' ");
		sql.append(" and main.gopay_txn_tm<to_timestamp(:paramTime, 'yyyymmddHH24miss') ");
		/*sql.append(" and main.gopay_txn_tm>to_timestamp(:paramTime, 'yyyymmddHH24miss') ");
		*//* 测试 *//*
		sql.append(" and main.gopay_order_id='2017120704439026' ");*/
		Map<String, Object> paramsMap = new HashMap<>(1);
		paramsMap.put("paramTime", paramTime);
		List<Object[]> rsList = commonQueryDAO.findBySql(sql.toString(), paramsMap);
		String orderId;
		if (rsList != null && rsList.size() > 0) {
			for (Object[] arr : rsList) {
				orderId = (String) arr[0];
				list.add(orderId);
			}
		}
		return list;
	}

}
